const Service = require('egg').Service;

let createRule = {
  password: {
    type: 'password',
    compare: 're-password',
  },
}

class UserService extends Service {


  async login(user) {
    const result = await this.app.mysql.beginTransactionScope(async conn => {
      let res = await this.ctx.app.mysql.get('sys_user', {
        username: user.username
      });
      if (res.length === 0) {
        throw new Error('手机号码不存在');
      }
      if (res.password !== user.password) {
        throw new Error('密码错误');
      }
      const user_id = res.user_id;
      let userLogin = {
        user_id: user_id,
        login_type: 1
      }
      const result1 = await this.ctx.app.mysql.insert('user_login', userLogin);
      if (result1.affectedRows !== 1) {
        throw new Error('登录失败');
      }
      return user_id
    }, this.ctx)
    return result;
  }


  async register(user) {
    const result = await this.app.mysql.beginTransactionScope(async conn => {
      let res = await conn.select('sys_user', {
        where: {
          username: user.username
        }
      });

      if (res.length !== 0) {
        throw new Error('手机号码已存在');
      }
      const result1 = await conn.insert('sys_user', user);
      if (result1.affectedRows !== 1) {
        throw new Error('注册失败');
      }
      let myuser = {
        phonenum: user.username
      }
      const result2 = await conn.insert('user', myuser);
      console.log(result2);
      if (result2.affectedRows !== 1) {
        throw new Error('注册失败');
      }

      const result3 = await conn.update('sys_user', { user_id: result2.insertId },
        {
          where: { username: user.username }
        });
      if (result3.affectedRows !== 1) {
        throw new Error('注册失败');
      }
      return ""
    }, this.ctx);
  }
  async update(user) {
    user.update_time = this.app.mysql.literals.now
    const result = await this.app.mysql.beginTransactionScope(async conn => {
      let res = await conn.update('user', user)
      if (res.affectedRows !== 1) {
        throw new Error('修改失败');
      }
      return ""
    }, this.ctx);
  }
  async updatePassword(user) {
    let res = await this.ctx.app.mysql.update('sys_user', user, { where: { user_id: user.user_id } })
    if (res.affectedRows !== 1) {
      throw new Error('修改失败');
    }
    return "";
  }

}

module.exports = UserService;